<?php
/**
 * YICMS
 * ============================================================================
 * 版权所有 2014-2017 YICMS，并保留所有权利。
 * 网站地址: http://www.yicms.vip
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Created by PhpStorm.
 * Author: kenuo
 * Date: 2017/11/17
 * Time: 下午4:40
 */

namespace App\Repositories\PayAndConsume;


use App\Models\PayLog;
use App\Models\TradeLog;
use \Illuminate\Pagination\Paginator;
use \Illuminate\Pagination\LengthAwarePaginator;


class PayRepository
{
    public function __construct(StatRepository $statRepository)
    {
        $this->statRepository = $statRepository;
    }

    /**
     * 获取 充值详情
     * @return mixed
     */
    public function getWithDetail($request)
    {
        $gameID = session('game_id');

        $query = [
            [
                '$match' => [
                    'pay_time' => [
                        '$gte' => $request['start_time'] . ' 00:00:00',
                        '$lte' => $request['end_time'] . ' 23:59:59'
                    ],
                    'game_id' => [
                        '$eq' => $gameID
                    ],
                    'unique_id' => [
                        '$in' => $request['unique_id']
                    ],
                    'uid' => [
                        '$eq' => $request['uid']
                    ],
                ]
            ],
            ['$project' =>
                [
                    'uid' => 1,
                    'account' => 1,
                    'level' => 1,
                    'nickname' => 1,
                    'register_time' => 1,
                    'pay_time' => 1,

                    'game_name' => 1,
                    'channel_name' => 1,
                    'server_name' => 1,

                    'amounts' => 1,
                    'item_name' => 1
                ]
            ],
        ];
        $query[] = ['$sort' => ['pay_time' => -1]];

        $collection = PayLog::raw(function ($collection) use ($query) {
            return $collection->aggregate($query);
        });

        return $collection;
    }

    /**
     * 获取全部的充值排行
     * @return mixed
     */
    public function getWithPayRank($request)
    {
        $gameID = session('game_id');
        $page = Paginator::resolveCurrentPage();
        $perPage = $request['page_size'];

        $query = [
            [
                '$match' => [
                    'pay_time' => [
                        '$gte' => $request['start_time'] . ' 00:00:00',
                        '$lte' => $request['end_time'] . ' 23:59:59'
                    ],
                    'game_id' => [
                        '$eq' => $gameID
                    ],
                    'unique_id' => [
                        '$in' => $request['unique_id']
                    ]
                ]
            ],
            ['$group' =>
                [
                    '_id' => '$uid',
                    'nickname' => [
                        '$last' => '$nickname'
                    ],
                    'account' => [
                        '$last' => '$account'
                    ],
                    'server_name' => [
                        '$last' => '$server_name'
                    ],
                    'level' => [
                        '$last' => '$level'
                    ],
                    'register_time' => [
                        '$last' => '$register_time'
                    ],
                    'pay_time' => [
                        '$last' => '$pay_time'
                    ],
                    'total_amounts' => [
                        '$sum' => [
                            '$toDouble' => '$amounts'
                        ]
                    ],
                    'pay_times' => [
                        '$sum' => 1
                    ],
                ]
            ],
        ];

        $collection = PayLog::raw(function ($collection) use ($query) {
            return $collection->aggregate($query);
        });
        $total = $collection->count();

        $query[] = ['$sort' => ['total_amounts' => -1]];
        $query[] = ['$skip' => ($page - 1) * $perPage];
        $query[] = ['$limit' => $perPage];

        $collection = PayLog::raw(function ($collection) use ($query) {
            return $collection->aggregate($query);
        });

        return new LengthAwarePaginator($collection, $total, $perPage, $page, [
            'path' => Paginator::resolveCurrentPath(),
        ]);
    }

    /**
     * 获取全部的交易日志
     * @return mixed
     */
    public function getWithTradeLog($request)
    {
        //$request['unique_id'], $request['start_time'], $request['end_time']
        $gameID = session('game_id');
        $page = Paginator::resolveCurrentPage();
        $perPage = $request['page_size'];

        $match = [
            'op_time' => [
                '$gte' => $request['start_time'] . ' 00:00:00',
                '$lte' => $request['end_time'] . ' 23:59:59'
            ],
            'game_id' => [
                '$eq' => $gameID
            ],
            'unique_id' => [
                '$in' => $request['unique_id']
            ]
        ];

        if ($request['trade_type'] > 0) {
            $match['trade_type'] = [
                '$eq' => $request['trade_type']
            ];
        }

        if (isset($request['account']) && $request['account'] != null) {
            $match['account'] = [
                '$eq' => $request['account']
            ];
        }

        if (isset($request['nickname']) && $request['nickname'] != null) {
            $match['nickname'] = [
                '$eq' => $request['nickname']
            ];
        }

        if (isset($request['uid']) && $request['uid'] != null) {
            $match['uid'] = [
                '$eq' => $request['uid']
            ];
        }

        $query = [
            [
                '$match' => $match
            ],
            ['$group' =>
                [
                    '_id' => [
                        'id' => '$uid',
                        'trade_type' => '$trade_type',
                    ],
                    'total_update_amount' => [
                        '$sum' => [
                            '$toDouble' => '$update_amount'
                        ]
                    ],
                    'channel_name' => [
                        '$last' => '$channel_name'
                    ],
                    'server_name' => [
                        '$last' => '$server_name'
                    ],
                    'server_id' => [
                        '$last' => '$server_id'
                    ],
                    'account' => [
                        '$last' => '$account'
                    ],
                    'nickname' => [
                        '$last' => '$nickname'
                    ],
                    'trade_type' => [
                        '$last' => '$trade_type'
                    ],
                    'trade_type_name' => [
                        '$last' => '$trade_type_name'
                    ],
                    'money_kinds_name' => [
                        '$last' => '$money_kinds_name'
                    ],
                ]
            ],
        ];

        $total_update_amount = [];
        if (isset($request['amount_from']) && $request['amount_from'] != null) {
            $total_update_amount['$gte'] = intval($request['amount_from']);
        }
        if (isset($request['amount_to']) && $request['amount_to'] != null) {
            $total_update_amount['$lte'] = intval($request['amount_to']);
        }
        if (count($total_update_amount) > 0) {
            $query[] = [
                '$match' => [
                    'total_update_amount' => $total_update_amount
                ]
            ];
        }

        $collection = TradeLog::raw(function ($collection) use ($query) {
            return $collection->aggregate($query);
        });
        $total = $collection->count();//计算总记录数

        $query[] = ['$sort' => ['_id' => -1]];
        $query[] = ['$skip' => ($page - 1) * $perPage];
        $query[] = ['$limit' => $perPage];

        $collection = TradeLog::raw(function ($collection) use ($query) {
            return $collection->aggregate($query);
        });

        return new LengthAwarePaginator($collection, $total, $perPage, $page, [
            'path' => Paginator::resolveCurrentPath(),
        ]);
    }

    /**
     * 获取全部的 充值档位统计
     * @return mixed
     */
    public function getWithGrade($request)
    {
        $gameID = session('game_id');

        $query = [
            [
                '$match' => [
                    'pay_time' => [
                        '$gte' => $request['start_time'] . ' 00:00:00',
                        '$lte' => $request['end_time'] . ' 23:59:59'
                    ],
                    'game_id' => [
                        '$eq' => $gameID
                    ],
                    'type' => [
                        '$in' => $request['type']
                    ],
                    'unique_id' => [
                        '$in' => $request['unique_id']
                    ],
                ]
            ],
            ['$group' =>
                [
                    '_id' => [
                        'item_name' => '$item_name',
                    ],
                    'amounts' => [
                        '$sum' => [
                            '$toDouble' => '$amounts'
                        ]
                    ],
                    'uid' => [
                        '$addToSet' => '$uid',
                    ],
                    'pay_times' => [
                        '$sum' => 1
                    ],
                ]
            ],
            [
                '$project' => [
                    '_id' => 0,
                    'item_name' => '$_id.item_name',
                    'amounts' => '$amounts',
                    'pay_times' => '$pay_times',
                    'pay_users' => [
                        '$size' => '$uid'
                    ],
                ]
            ],
            [
                '$sort' =>
                    [
                        'amounts' => -1
                    ]
            ]
        ];

        $collection = PayLog::raw(function ($collection) use ($query) {
            return $collection->aggregate($query);
        });

        $data = $collection->toArray();//计算总记录数

        //求 总支付次数   总支付用户数
        $total = $this->statRepository->getTotalPayUsersAndTotalPayTimes($request)->toArray();
        $totalPayTimes = isset($total[0]) ? $total[0]['total_pay_times'] : 0;
        $totalPayUsers = isset($total[0]) ? $total[0]['total_pay_users'] : 0;

        foreach ($data as $key => $value) {
            //在第一行数据中添加上,总人数,总支付次数,用来在前台显示
            if ($key == 0) {
                $data[$key]['total_pay_times'] = $totalPayTimes;
                $data[$key]['total_pay_users'] = $totalPayUsers;
            }

            if ($totalPayTimes > 0) {
                $data[$key]['pay_times_rate'] = round($value['pay_times'] / $totalPayTimes * 100, 2);
            }
            if ($totalPayUsers > 0) {
                $data[$key]['pay_users_rate'] = round($value['pay_users'] / $totalPayUsers * 100, 2);
            }
        }

        return $data;
    }

    /**
     * 获取全部的 充值类型
     * @return mixed
     */
    public function getWithPayLogType()
    {
        $gameID = session('game_id');

        $query = [
            [
                '$match' =>
                    [
                        'game_id' =>
                            [
                                '$eq' => $gameID
                            ],
                    ]
            ],
            [
                '$group' =>
                    [
                        '_id' =>
                            [
                                'type' => '$type',
                            ],
                        'type_name' =>
                            [
                                '$last' => '$type_name'
                            ],
                    ]
            ],
            [
                '$sort' =>
                    [
                        '_id.type' => 1
                    ]
            ]
        ];

        $collection = PayLog::raw(function ($collection) use ($query) {
            return $collection->aggregate($query);
        });

        $data = $collection->toArray();
        $formatData = [];
        foreach ($data as $key => $value) {
            $formatData[] = [
                'type' => $value['_id']['type'],
                'type_name' => $value['type_name'],
            ];
        }

        return $formatData;
    }
}